
cc.Class({
    extends: cc.Component,

    properties: {
        // 其他属性
        reConnectTimes: 1,
        isReContent: true,
    },

    netWorkInit(config) {
        this.config = config;
        const serverIp = this.config.serverIp;
        const port_lobby = this.config.port_lobby;
        this.lobbyMain = this.node.getComponent("lobbyMain");
        this.playerInfo = this.lobbyMain.playerInfo;
        let playerId = this.playerInfo.playerId;
        let self = this;
        let reconnectTimeout;  //重连定时器
        // self.socket = new WebSocket(`ws://${serverIp}:${port_lobby}`);
        self.socket = new WebSocket(`ws://${serverIp}:${port_lobby}`, [playerId]);

        self.socket.onopen = () => {
            console.log('🚀服务器连接成功');
            clearTimeout(reconnectTimeout);
            self.lobbyMain.contentSuccess();
            self.reConnectTimes = 0;
            self.lobbyMain.loading.active = false;
        };

        self.socket.onmessage = (event) => {
            const data = JSON.parse(event.data);
            switch (data.action) {
                case "login":  // 登录
                    self.lobbyMain.onLoginResponse(data.data);
                    break;
                case "reg":   // 注册
                    self.lobbyMain.onRegResponse(data.data);
                    break;
                case "changeHead":  // 修改头像
                    self.lobbyMain.settingScript.onChangeHeadResponse(data.data);
                    break;
                case "changePsw":  // 修改密码
                    self.lobbyMain.settingScript.onChangePsw(data.data);
                    break;
                case "config":   // 获取配置
                    self.lobbyMain.onGetConfig(data.data);
                    break;
                case "updatePlayerInfo":   // 更新玩家信息
                    self.lobbyMain.updatePlayerInfo(data.data);
                    break;
                case "gameStatusUpdated":   // 游戏状态更新
                    self.lobbyMain.gameContent.gameStatusUpdated(data.data);
                    break;
                case "getBetRecord":   // 获取投注稽核
                    self.lobbyMain.betRecordScript.onGetBetRecord(data.data);
                    break;
                case "getBetHistory":   // 获取投注历史记录
                    self.lobbyMain.betHistoryScript.onGetBetHistory(data.data);
                    break;
                case "updateMessageList":   // 更新走马灯消息
                    self.lobbyMain.messageJs.onUpdateMessage(data.data);
                    break;
                case "tuisong":   // 右上角的大奖推送
                    self.lobbyMain.tuisongJs.onTuiSongWin(data.data);
                    break;
                case "readEmail":   // 已读邮件的返回
                    self.lobbyMain.emailScript.onReadEmailResponse(data.data);
                    break;
                case "receiveEmail":   // 接收邮件的返回
                    self.lobbyMain.emailScript.onReceiveEmailResponse(data.data);
                    break;
                case "deleteEmail":   // 删除邮件的返回
                    self.lobbyMain.emailScript.onDeleteEmailResponse(data.data);
                    break;
                case "newMail":   // 有新邮件
                    self.lobbyMain.onNewMailResponse(data.data, data.isRecharge);
                    break;
                case "getDaily":   // 每日转盘获取
                    self.lobbyMain.dailyScript.onGetDailyRes(data.data);
                    break;
                case "daily":   // 每日转盘处理
                    self.lobbyMain.dailyScript.onDaily(data.data);
                    break;
                case "getRedeemConfig":   // 获取提现配置
                    self.lobbyMain.redeemScript.onRedeemConfig(data.data);
                    break;
                case "changeCashTag":   // 修改CashTag
                    self.lobbyMain.redeemScript.onChangeCashTag(data.data);
                    break;
                case "quickStart":   // 快速登录返回
                    self.lobbyMain.onQuickStart(data.data);
                    break;
                case "bindAccount":   // 绑定账号返回
                    self.lobbyMain.settingScript.onbindAccount(data.data);
                    break;
                case "getKefuUrl":   // 获取客服地址返回
                    self.lobbyMain.kefuScript.onKefuUrl(data.data);
                    break;
                case "getEventData":   // 获取活动返回
                    self.lobbyMain.eventScript.onEventData(data.data);
                    break;
                case "getRechargeChannel":   // 获取充值通道返回
                    self.lobbyMain.shopScript.onRechargeChannel(data.data);
                    break;
                case "getRechargeRecord":   // 获取充值记录返回
                    self.lobbyMain.shopScript.onRechargeRecord(data.data);
                    break;
                case "getVipInfo":   // 获取VIP信息返回
                    self.lobbyMain.vipScript.onVipInfo(data.data);
                    break;
                case "receiveVipBonus":   // 获取VIP信息返回
                    self.lobbyMain.vipScript.onVipBonusResult(data.data);
                    break;
                case "getTotalRecharge":   // 查询总充值返回
                    self.lobbyMain.onTotalRechargeResult(data.data);
                    break;
                case "bindAgent":   // 绑定代理返回
                    self.lobbyMain.bindAgentScript.onBindAgentResult(data.data);
                    break;
                case "getFirstRechargeInfo":   // 获取首充信息返回
                    self.lobbyMain.firstRechargeScript.onFirstRechargeInfoResult(data.data);
                    break;
                case "getOrderRecord":   // 获取提现订单返回
                    if (self.lobbyMain.redeemScript) {
                        self.lobbyMain.redeemScript.onOrderRecordResult(data.data);
                    }
                    if (data.data.coin) {
                        if (data.data.coin / self.playerInfo.ratio != self.playerInfo.playerCoin) {
                            self.playerInfo.playerCoin = data.data.coin / self.playerInfo.ratio;
                            self.lobbyMain.updateUserCoin();
                        }
                    }
                    break;
                case "getPlayerCoin":   // 获取玩家金币返回
                    if (data.data) {
                        self.playerInfo.playerCoin = data.data / self.playerInfo.ratio;
                    }
                    self.lobbyMain.updateUserCoin();

                    break;
                case "getAllSons":   // 获取玩家子玩家返回
                    self.lobbyMain.sendGiftsScript.onGetAllSons(data.data);
                    break;
                default:
                    break;
            }
            if (data.action != "tuisong") {
                // console.log('🌟Received:', JSON.stringify(data));
                console.log('🌟Received:', data);
            }
        };

        self.socket.onerror = (error) => {
            console.error('与服务端连接报错:', JSON.stringify(error));
        };

        self.socket.onclose = (event) => {
            console.log('⚠️与服务端连接断开！');
            self.lobbyMain.openLoading("reconnecting");

            if (self.isReContent) {
                reconnectTimeout = setTimeout(() => {
                    console.log('第 ' + self.reConnectTimes + ' 次尝试重新连接...');
                    self.reConnectTimes++;
                    self.onDestroy();
                    self.netWorkInit(this.config)
                }, 5000);
            }
        };
    },

    // 向服务器发送数据
    sendMessage(message) {
        this.socket.send(JSON.stringify(message));
    },

    // 销毁 WebSocket 连接
    onDestroy() {
        if (this.socket) {
            this.socket.close();
        }
    },

    //向服务器发送post请求
    sendPost(name, data, callback) {
        data = JSON.stringify(data)
        const serverIp = this.config.serverIp;
        const port_lobby = this.config.port_lobby;
        const url = `http://${serverIp}:${port_lobby}/${name}`;

        const xhr = new XMLHttpRequest();
        xhr.open("POST", url, true);
        xhr.setRequestHeader("Content-Type", "application/json");

        let self = this;
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4) {
                self.lobbyMain.loading.active = false;
                if (xhr.status >= 200 && xhr.status < 300) {
                    let res = JSON.parse(xhr.responseText);
                    console.log('🤑请求成功:', res);
                    if (callback) callback(res);
                } else {
                    console.error("请求失败：", xhr.status, xhr.responseText);
                }
            }
        };
        xhr.send(data);
    },


});
